﻿//#define Net45 //如果使用net45的库, 请定义这里
//#define USE_JSON
#define USE_WINFORM
//#define USE_COMBOBOXRELPATH

#if(USE_JSON)
using Newtonsoft.Json;
#endif
#if(USE_WINFORM)
using System.Windows.Forms;
#endif

using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
#if Net45
using System.Threading.Tasks;
#endif

namespace SarjetLib
{
  /// <summary>
  /// 不依赖函数
  /// </summary>
  public class CHlpListView
  {
    public enum SortOrientation
    {
      Default = 0,
      Ascending,
      Declineing,
    }

    public class ListViewColumnSorter : IComparer
    {
      /// <summary>
      /// 指定按照哪个列排序
      /// </summary>
      private int ColumnToSort;

      /// <summary>
      /// 指定排序的方式
      /// </summary>
      private SortOrder OrderOfSort;

      /// <summary>
      /// 声明CaseInsensitiveComparer类对象，
      /// 参见ms-help://MS.VSCC.2003/MS.MSDNQTR.2003FEB.2052/cpref/html/frlrfSystemCollectionsCaseInsensitiveComparerClassTopic.htm
      /// </summary>
      private CaseInsensitiveComparer ObjectCompare;

      /// <summary>
      /// 构造函数
      /// </summary>
      public ListViewColumnSorter()
      {
        // 默认按第一列排序
        ColumnToSort = 0;

        // 排序方式为不排序
        OrderOfSort = SortOrder.None;

        // 初始化CaseInsensitiveComparer类对象
        ObjectCompare = new CaseInsensitiveComparer();
      }

      /// <summary>
      /// 重写IComparer接口.
      /// </summary>
      /// <param name="x">要比较的第一个对象</param>
      /// <param name="y">要比较的第二个对象</param>
      /// <returns>比较的结果.如果相等返回0，如果x大于y返回1，如果x小于y返回-1</returns>
      public int Compare(object x, object y)
      {
        int compareResult;
        ListViewItem listviewX, listviewY;

        // 将比较对象转换为ListViewItem对象
        listviewX = (ListViewItem)x;
        listviewY = (ListViewItem)y;

        // 比较
        //compareResult = ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text, listviewY.SubItems[ColumnToSort].Text);
        compareResult = StringCompare_LengthPrioity(listviewX.SubItems[ColumnToSort].Text, listviewY.SubItems[ColumnToSort].Text);

        // 根据上面的比较结果返回正确的比较结果
        if (OrderOfSort == SortOrder.Ascending)
        {
          // 因为是正序排序，所以直接返回结果
          return compareResult;
        }
        else if (OrderOfSort == SortOrder.Descending)
        {
          // 如果是反序排序，所以要取负值再返回
          return (-compareResult);
        }
        else
        {
          // 如果相等返回0
          return 0;
        }
      }

      /// <summary>
      /// 获取或设置按照哪一列排序.
      /// </summary>
      public int SortColumn
      {
        set { ColumnToSort = value; }
        get { return ColumnToSort; }
      }

      /// <summary>
      /// 获取或设置排序方式.
      /// </summary>
      public SortOrder Order
      {
        set { OrderOfSort = value; }
        get { return OrderOfSort; }
      }
    }
    public bool rev = false;
    public int prevSortColumn;
    public ListView lsvView;

  #region ListView控件
    /// <summary>
    /// 控件缓冲区
    /// </summary>
    //private static List<Control> lstBuffer;

    private ListViewColumnSorter lvwColumnSorter = new ListViewColumnSorter();

    public CHlpListView(ListView lsvView)
    {
      prevSortColumn = -1;
      this.lsvView = lsvView;
    }

    public void SortByColumn<T>(List<T> lsStruct, Func<T, ListViewItem> lvi, ColumnClickEventArgs columnArgs)
    {
      if (prevSortColumn == columnArgs.Column)
      {
        rev = !rev;
      }
      else
      {
        prevSortColumn = columnArgs.Column;
      }
      lsStruct.Sort(new Comparison<T>((a, b) =>
      {
        string ast = lvi(a).SubItems[columnArgs.Column].Text;
        string bst = lvi(b).SubItems[columnArgs.Column].Text;
        double adst;
        double bdst;
        double.TryParse(lvi(a).SubItems[columnArgs.Column].Text, out adst);
        double.TryParse(lvi(b).SubItems[columnArgs.Column].Text, out bdst);
        int v;
        switch (columnArgs.Column)
        {
          case 2:
          case 3:
          case 4:
          case 5:
            v = adst - bdst > 0 ? 1 : (adst - bdst < 0 ? -1 : 0);
            break;
          default:
            v = ast.CompareTo(bst);
            break;
        }
        return rev ? -v : v;
      }));
      this.lsvView.Refresh();
    }

    /// <summary>
    /// lv丢失焦点后仍然保持高亮, 绑定事件
    /// </summary>
    /// <param name="lv">listview</param>
    public static void lsvLostFocusHighlightItemBind(ListView lv)
    {
      lv.ItemSelectionChanged += ((s, e) => lsvLostFocusHighlightItem(e.Item));
      lv.Validated += ((s, e) => lsvLostFocusHighlightItem(lv.FocusedItem));
    }

    /// <summary>
    /// 设置lv丢失焦点后仍然保持高亮
    /// </summary>
    /// <param name="lvi">listviewitem</param>
    public static void lsvLostFocusHighlightItem(ListViewItem lvi)
    {
      if (lvi == null)
      {
        return;
      }
      if (!lvi.Selected)
      {
        lvi.BackColor = SystemColors.Window;
        lvi.ForeColor = Color.Black;
      }
      else
      {
        lvi.BackColor = SystemColors.Highlight;
        lvi.ForeColor = Color.White;
      }
    }

    /// <summary>
    /// 获取正则括号的第一个数
    /// </summary>
    /// <param name="s">目标</param>
    /// <param name="rgx">正则表达, 如@"->(\d)", 表示获取(\d)的数</param>
    /// <returns>返回结果</returns>
    public static int GetRegexGroupNum(string s, string rgx)
    {
      int geti;
      MatchCollection mc = Regex.Matches(s, rgx);
      if (mc.Count > 0)
      {
        geti = StringToInt(mc[0].Groups[1].Value);
      }
      else
      {
        geti = -1;
      }
      return geti;
    }

    /// <summary>
    /// 遍历选中的项并修改
    /// </summary>
    /// <param name="lsvctl"></param>
    /// <param name="lviAction">修改的方法</param>
    /// <param name="from"></param>
    /// <param name="to"></param>
    public static void ForeachItems(ListView lsvctl, Action<ListViewItem> lviAction, int from = 0, int to = -1)
    {
      if (to == -1)
      {
        to = lsvctl.Items.Count;
      }
      for (int i = from; i < to; i++)
      {
        lviAction(lsvctl.Items[i]);
      }
    }

    /// <summary>
    /// 根据Regex的数寻找上下顺序的项并选中
    /// </summary>
    /// <param name="lsvControl">listview</param>
    /// <param name="SubitemIndex">第几列</param>
    /// <param name="rgxGroupSelect">遍历的正则方法</param>
    /// <returns>返回是否成功</returns>
    /// 例如: 1:档位P->1, 2:档位P->2, 3:档位P->3, 如果当前选择的是2, 则会选中1~3
    public static bool SelectFollowRegexNumber(ListView lsvControl, int SubitemIndex, string rgxGroupSelect = @"->(\d)")
    {
      if (lsvControl.SelectedItems.Count == 0)
      {
        return false;
      }
      var s = lsvControl.SelectedItems[0].SubItems[SubitemIndex].Text;
      var cnt = lsvControl.Items.Count;
      var ind = lsvControl.SelectedItems[0].Index;
      var ind2 = ind;
      int d, drec, d2 = 0;
      d = drec = GetRegexGroupNum(s, rgxGroupSelect);
      if (d != -1)
      {
        while (d > 0 && ind > 0)
        {
          ind--;
          d2 = GetRegexGroupNum(lsvControl.Items[ind].SubItems[SubitemIndex].Text, rgxGroupSelect);
          if (ind != -1 && d2 != -1 && d2 < d)
          {
            d = d2;
            lsvControl.Items[ind].Selected = true;
          }
          else
          {
            break;
          }
        }
        while (true)
        {
          ind2++;
          if (ind2 < cnt)
          {
            d2 = GetRegexGroupNum(lsvControl.Items[ind2].SubItems[SubitemIndex].Text, rgxGroupSelect);
            if (d2 != -1 && d2 > d)
            {
              d = d2;
              lsvControl.Items[ind2].Selected = true;
            }
            else
            {
              break;
            }
          }
          else
          {
            break;
          }
        }
      }
      return true;
    }

    /// <summary>
    /// 获取所有选择的项
    /// </summary>
    /// <param name="lsvGet">ListView控件</param>
    /// <returns>所有项</returns>
    public static string[] GetAllSelections(ListView lsvGet)
    {
      if (lsvGet.SelectedItems.Count == 0) { return null; }

      string[] files = new string[lsvGet.SelectedItems.Count];
      int i = 0;
      foreach (ListViewItem item in lsvGet.SelectedItems)
      {
        files[i++] = item.Text;
      }
      return files;
    }

    /// <summary>
    /// 设置 Listview 高度
    /// </summary>
    /// <param name="lsv">控件</param>
    public static void SetItemsHight(ListView lsv, int Height)
    {
      ImageList imgList = new ImageList()
      {
        ImageSize = new Size(1, Height)
      };
      lsv.SmallImageList = imgList;
      lsv.GridLines = true;
      lsv.FullRowSelect = true;
      lsv.View = View.Details;
      lsv.Scrollable = true;
      lsv.MultiSelect = false;
    }

    /// <summary>
    /// 自动处理指定列宽
    /// </summary>
    /// <param name="dget">控件</param>
    /// <param name="selectColumn">指定列</param>
    public static void AutoSizeColumn(ListView dget, int selectColumn)
    {
      EventHandler e = new EventHandler((object s, EventArgs e1) =>
      {
        Thread t = new Thread(() =>
              {
                Thread.Sleep(10);
                try
                {
                  dget.Parent.Invoke((MethodInvoker)(() =>
                        {
                          ListviewResize(dget, selectColumn);
                        }));
                }
                catch { }
              });
        t.IsBackground = true;
        t.Start();
      });
      dget.GotFocus += e;
      dget.Resize += e;
    }

    private static void ListviewResize(ListView dget, int selectColumn, int leaseWidth = 100)
    {
      try
      {
        int keepWidth = 30;
        int width = 0;
        int getwidth;
        for (int i = 0; i < dget.Columns.Count; i++)
        {
          if (selectColumn != i)
          {
            width += dget.Columns[i].Width;
          }
        }
        getwidth = dget.Width - width - keepWidth;
        if (getwidth > leaseWidth) { dget.Columns[selectColumn].Width = getwidth; }
        else { dget.Columns[selectColumn].Width = leaseWidth; }
      }
      catch { }
    }


    /// <summary>
    /// 批量获取listview的值
    /// </summary>
    /// <param name="ls"></param>
    /// <param name="column">指定行</param>
    /// <param name="len">数量</param>
    /// <param name="offset">偏移量</param>
    /// <returns></returns>
    public static string[] GetItemsArray(ListView ls, int column, int len = -1, int offset = 0)
    {
      //如果为空或者偏移量大于长度, 判定offset长度是否超过原数组: 标准写法.....find
      if (ls == null || offset >= ls.Items.Count) { return new string[0]; }
      else if (len == -1) { len = ls.Items.Count - offset; }
      string[] stmp = new string[len];
      for (int i = 0; i < ls.Items.Count; i++)
      {
        stmp[i] = ls.Items[offset + i].SubItems[column].Text;
      }
      return stmp;
    }

    /// <summary>
    /// ListView排序
    /// </summary>
    /// <param name="lsvGet">ListView控件</param>
    /// <param name="Column">标签</param>
    /// <param name="sroGet">排序顺序</param>
    public void SortEvent(int Column, SortOrder sroGet)
    {
      lsvView.ColumnClick += new ColumnClickEventHandler((object s, ColumnClickEventArgs e) =>
      {
        if (Column == -1 || e.Column == Column)
        {
          Sort(e.Column, sroGet);
        }
      });
    }

    /// <summary>
    /// ListView自动排序
    /// </summary>
    /// <param name="lsvGet">ListView控件</param>
    /// <param name="Column">标签</param>
    public void SortEvent(int Column = -1)
    {
      lsvView.ColumnClick += new ColumnClickEventHandler((object s, ColumnClickEventArgs e) =>
      {
        if (Column == -1 || e.Column == Column)
        {
          Sort(e.Column);
        }
      });
    }

    /// <summary>
    /// ListView排序
    /// </summary>
    /// <param name="lsvGet">ListView控件</param>
    /// <param name="Column">标签</param>
    /// <param name="sroGet">排序顺序</param>
    public void Sort(int Column, SortOrder sroGet)
    {
      lvwColumnSorter.SortColumn = Column;
      lsvView.ListViewItemSorter = lvwColumnSorter;
      lsvView.Sorting = sroGet;
      lvwColumnSorter.Order = sroGet;
      lsvView.Sort();
    }

    /// <summary>
    /// ListView自动排序
    /// </summary>
    /// <param name="lsvGet">ListView控件</param>
    /// <param name="Column">标签</param>
    public void Sort(int Column)
    {
      // 创建一个ListView排序类的对象，并设置listView1的排序器
      lsvView.ListViewItemSorter = lvwColumnSorter;

      if (Column == lvwColumnSorter.SortColumn)
      {
        // 重新设置此列的排序方法.
        if (lvwColumnSorter.Order == SortOrder.Ascending)
        {
          lsvView.Sorting = SortOrder.Descending;
          lvwColumnSorter.Order = SortOrder.Descending;
        }
        else
        {
          lsvView.Sorting = SortOrder.Ascending;
          lvwColumnSorter.Order = SortOrder.Ascending;
        }
      }
      else
      {
        // 设置排序列，默认为正向排序
        lvwColumnSorter.SortColumn = Column;
        if (lvwColumnSorter.Order == SortOrder.Ascending)
        {
          lsvView.Sorting = SortOrder.Descending;
          lvwColumnSorter.Order = SortOrder.Descending;
        }
        else
        {
          lsvView.Sorting = SortOrder.Ascending;
          lvwColumnSorter.Order = SortOrder.Ascending;
        }
        //lvwColumnSorter.Order = SortOrder.Ascending;
      }

      // 用新的排序方法对ListView排序
      lsvView.Sort();
    }

    /// <summary>
    /// Listview专用文本转换为Listview
    /// </summary>
    /// <param name="ls">控件</param>
    /// <param name="s">专用文本</param>
    /// <returns>返回数量</returns>
    public static int TextToList(ListView ls, string s, int lcnt, string newline = "\r\n")
    {
      if (s == null || s == "") { return 0; }
      //int sum = -1;
      string list;
      string[] sdata, dat;
      ls.Items.Clear();
      sdata = Split(s, newline);
      for (int i = 0; i < sdata.Length; i++)
      {
        list = sdata[i];
        //if (sum == -1)
        //{
        //    sum = CString.CountAInB(list, "::");
        //}
        dat = Split(list, "::");
        if (lcnt == -1 || dat.Length == lcnt)
        {
          ls.Items.Add(new ListViewItem(dat));
        }
      }
      return sdata.Length;
    }

    /// <summary>
    /// Listview转换为专用文本
    /// </summary>
    /// <param name="ls">控件</param>
    /// <returns>返回专用文本</returns>
    public static string ListToText(ListView ls, string newline = "\r\n")
    {
      StringBuilder sbCreat = new StringBuilder();
      for (int i = 0; i < ls.Items.Count; i++)
      {
        for (int j = 0; j < ls.Items[i].SubItems.Count; j++)
        {
          if (j == ls.Items[i].SubItems.Count - 1)
          {
            sbCreat.Append(ls.Items[i].SubItems[j].Text);
          }
          else
          {
            sbCreat.Append(ls.Items[i].SubItems[j].Text + "::");
          }
        }
        if (ls.Items[i].SubItems.Count > 0 && i != ls.Items.Count - 1)
        {
          sbCreat.Append(newline);
        }
      }
      return sbCreat.ToString();
    }

    /// <summary>
    /// Listview添加一行全部赋值""
    /// </summary>
    /// <param name="lsvGet">Listview控件</param>
    public static void AddItemLine(ListView lsvGet)
    {
      AddItemLine(lsvGet, "");
    }

    /// <summary>
    /// Listview添加一行全部赋值""
    /// </summary>
    /// <param name="lsvGet">Listview控件</param>
    /// <param name="sFirstText">第一行标题</param>
    public static void AddItemLine(ListView lsvGet, string sFirstText)
    {
      List<string> lstNew = new List<string>();
      lstNew.Add(sFirstText);
      for (int i = 1; i < lsvGet.Columns.Count; i++)
      {
        lstNew.Add("");
      }
      lsvGet.Items.Add(new ListViewItem(lstNew.ToArray()));
    }

    /// <summary>
    /// Listview添加一行全部赋值""
    /// </summary>
    /// <param name="lsvGet">Listview控件</param>
    /// <param name="sText">列表</param>
    public static ListViewItem AddItemLine(ListView lsvGet, string[] sText)
    {
      ListViewItem ls = new ListViewItem(sText);
      lsvGet.Items.Add(ls);
      return ls;
    }

    /// <summary>
    /// 找到Listview第一个选中的行,无则返回-1
    /// </summary>
    /// <param name="lsvGet">Listview控件</param>
    /// <returns>行数</returns>
    public static int lsvFindSelectFirstIndex(ListView lsvGet)
    {
      return lsvGet.SelectedIndices[0];
      //for (int i = 0; i < lsvGet.Items.Count; i++)
      //{
      //	if (lsvGet.Items[i].Selected) { return i; }
      //}
      //return -1;
    }

    /// <summary>
    /// 移动Listview项到某行
    /// </summary>
    /// <param name="lsvGet">Listview控件</param>
    /// <param name="intMoveTo">第几行,0开始</param>
    public static void SelectIndexBackColor(ListView lsvGet, int Index, Color c, Color defc)
    {
      for (int i = 0; i < lsvGet.Items.Count; i++)
      {
        if (i == Index)
        {
          lsvGet.Items[i].BackColor = c;
        }
        else
        {
          lsvGet.Items[i].BackColor = defc;
        }
      }
    }

    /// <summary>
    /// 移动Listview项到某行
    /// </summary>
    /// <param name="lsvGet">Listview控件</param>
    /// <param name="intMoveTo">第几行,0开始</param>
    public static void SelectIndex(ListView lsvGet, int Index = -1)
    {
      for (int i = 0; i < lsvGet.Items.Count; i++)
      {
        if (i == Index)
        {
          lsvGet.Items[i].Selected = true;
        }
        else
        {
          lsvGet.Items[i].Selected = false;
        }
      }
    }

    /// <summary>
    /// 移动Listview项到某行
    /// </summary>
    /// <param name="lsvGet">Listview控件</param>
    /// <param name="MoveTo">第几行,0开始</param>
    public static void SelectItemMoveTo(ListView lsvGet, int Start, int MoveTo)
    {
      ListViewItem lvi = lsvGet.Items[Start];
      lsvGet.Items[Start].Remove();
      lsvGet.Items.Insert(MoveTo, lvi);
    }

    /// <summary>
    /// 移动Listview选中的第一项到某行
    /// </summary>
    /// <param name="lsvGet">Listview控件</param>
    /// <param name="MoveTo">第几行,0开始</param>
    public static void SelectItemMoveTo(ListView lsvGet, int MoveTo)
    {
      SelectItemMoveTo(lsvGet, lsvGet.SelectedIndices[0], MoveTo);
    }

    /// <summary>
    /// 移动Listview选中的第一项到某行
    /// </summary>
    /// <param name="lsvGet">Listview控件</param>
    /// <param name="MoveToSite">第几行,0开始</param>
    public static void ContinusSelectItemsMoveTo(ListView lsvGet, int from, int len, int MoveToSite)
    {
      ListViewItem[] lvi = new ListViewItem[len];
      for (int i = 0; i < len; i++)
      {
        lvi[i] = lsvGet.Items[from + i];
      }
      for (int i = 0; i < len; i++)
      {
        lsvGet.Items[from].Remove();
      }
      for (int i = 0; i < len; i++)
      {
        lsvGet.Items.Insert(MoveToSite + i, lvi[i]);
      }
    }

    /// <summary>
    /// 移动Listview选中的第一项到某行
    /// </summary>
    /// <param name="lsvGet">Listview控件</param>
    /// <param name="MoveToSite">+x向下移x项动, -x向上移动x项</param>
    public static void ContinusSelectItemsMoveOffset(ListView lsvGet, int from, int len, int MoveToSite)
    {
      int temp;
      if (len <= 0)
      {
        return;
      }
      if (MoveToSite < 0)
      {
        MoveToSite = -MoveToSite;
        if (from < MoveToSite)
        {
          MoveToSite = from;
        }
        MoveToSite = from - MoveToSite;
        if (from == 0 && MoveToSite == 0)
        {
          return;
        }
      }
      else if (MoveToSite > 0)
      {
        temp = lsvGet.Items.Count - from - len;
        if (temp < MoveToSite)
        {
          MoveToSite = temp;
        }
        MoveToSite = from + MoveToSite;
        if (temp == 0 && MoveToSite + len == lsvGet.Items.Count)
        {
          return;
        }
      }

      lsvGet.BeginUpdate();
      ContinusSelectItemsMoveTo(lsvGet, from, len, MoveToSite);
      lsvGet.EndUpdate();
      for (int i = 0; i < len; i++)
      {
        lsvGet.Items[i + MoveToSite].Selected = true;
      }
    }

    /// <summary>
    /// 交换Listview的某两行
    /// </summary>
    /// <param name="lsvGet">Listview控件</param>
    /// <param name="A">行A</param>
    /// <param name="B">行B</param>
    public static void SwapLine(ListView lsvGet, int A, int B)
    {
      if (A + 1 > lsvGet.Items.Count || B > lsvGet.Items.Count) { return; }
      for (int i = 0; i < lsvGet.Columns.Count; i++)
      {
        try
        {
          string sA, sB;
          sA = lsvGet.Items[A].SubItems[i].Text;
          sB = lsvGet.Items[B].SubItems[i].Text;
          Swap(ref sA, ref sB);
          lsvGet.Items[A].SubItems[i].Text = sA;
          lsvGet.Items[B].SubItems[i].Text = sB;
        }
        catch
        { }
      }
    }

    /// <summary>
    /// 移除相同的项 Listview
    /// </summary>
    /// <param name="lsvGet">列表</param>
    public static int lsvRemoveSame(ListView lsvGet)
    {
      int Current = 0, CurrentCompare;
      int Count = 0;
      while (Current < lsvGet.Items.Count)
      {
        CurrentCompare = Current + 1;
        while (CurrentCompare < lsvGet.Items.Count)
        {
          if (lsvGet.Items[Current].ToString() == lsvGet.Items[CurrentCompare].ToString())
          {
            Count++;
            lsvGet.Items.RemoveAt(CurrentCompare);
            continue;
          }
          CurrentCompare++;
        }
        Current++;
      }
      return Count;
    }

    /// <summary>
    /// ListView包含关系添加
    /// </summary>
    /// <param name="lsvItem">ListView控件</param>
    /// <param name="dGet">目录或文件数组</param>
    public static string lsvItemsAddFileFolder(ListView lsvItem, string[] dGet, string newline = "\r\n")
    {
      string sNew = "";
      for (int i = 0; i < dGet.Length; i++)
      {
        string sNew2 = lsvItemsAddFileFolder(lsvItem, dGet[i]);
        if (sNew2 != "") { sNew += sNew2 + newline; }
      }
      return sNew;
    }

    /// <summary>
    /// ListView包含关系添加
    /// </summary>
    /// <param name="lsvItem">ListView控件</param>
    /// <param name="dGet">目录或文件</param>
    public static string lsvItemsAddFileFolder(ListView lsvItem, string dGet, string newline = "\r\n")
    {
      if (dGet.Trim() == "") { return ""; }
      for (int i = 0; i < lsvItem.Items.Count; i++)
      {
        if (dGet.IndexOf(lsvItem.Items[i].SubItems[0].Text) >= 0)
        {
          //MessageBox.Show(this, "包含关系,文件或目录被包含 [ " + lsvItem.Items[i].SubItems[0].Text + " ]", "文件或目录被包含", MessageBoxButtons.OK, MessageBoxIcon.Information);
          return lsvItem.Items[i].SubItems[0].Text;
        }
      }
      int nItemSite = 0;
      string sDeleteDir = "";
      while (nItemSite != lsvItem.Items.Count)
      {
        if (lsvItem.Items[nItemSite].SubItems[0].Text.IndexOf(dGet) >= 0)
        {
          sDeleteDir += lsvItem.Items[nItemSite].Text + newline;
          lsvItem.Items[nItemSite].Remove();
        }
        else { nItemSite++; }
      }
      if (sDeleteDir != "")
      {
        //MessageBox.Show(this, "由于包含关系,以下文件或目录被移除:" + newline + strDeleteDir, "文件或目录被包含", MessageBoxButtons.OK, MessageBoxIcon.Information);
        return sDeleteDir;
      }
      string[] strSet = new string[lsvItem.Columns.Count];
      for (int i = 0; i < lsvItem.Columns.Count; i++)
      {
        strSet[i] = "";
      }
      strSet[0] = dGet;
      lsvItem.Items.Add(new ListViewItem(strSet));
      return "";
    }

    /// <summary>
    /// 查询选中项是否连续的
    /// </summary>
    /// <param name="lsv">控件</param>
    /// <param name="from">开始项</param>
    /// <returns></returns>
    public static int lsvIsSelectItemsSeries(ListView lsv, out int from)
    {
      int start = 0;
      if (lsv.SelectedIndices.Count == 0)
      {
        from = -1;
        return -1;
      }
      else if (lsv.SelectedIndices.Count == 1)
      {
        from = lsv.SelectedIndices[0];
        return 1;
      }
      for (int i = 0; i < lsv.SelectedIndices.Count; i++)
      {
        if (i == 0)
        {
          start = lsv.SelectedIndices[i];
        }
        else
        {
          if (lsv.SelectedIndices[i] != start + i)
          {
            from = 0;
            return -1;
          }
        }

      }
      from = lsv.SelectedIndices[0];
      return lsv.SelectedIndices.Count;
    }

    /// <summary>
    /// ListView全选
    /// </summary>
    /// <param name="lsvGet">ListView控件</param>
    /// <param name="e">按键e事件</param>
    public static void SelectAll(ListView lsvGet)
    {
      lsvGet.KeyDown += new KeyEventHandler((object s, KeyEventArgs e1) =>
      {
        SelectAll(lsvGet, e1);
      });
    }


    /// <summary>
    /// ListView全选
    /// </summary>
    /// <param name="lsvGet">ListView控件</param>
    /// <param name="e">按键e事件</param>
    public static void SelectAll(ListView lsvGet, KeyEventArgs e)
    {
      if (e.KeyCode == Keys.A && e.Control == true)
      {
        for (int i = 0; i < lsvGet.Items.Count; i++)
        {
          lsvGet.Items[i].Selected = true;
        }
      }
    }

    private static void ehndl_KeyUp(object sender, KeyEventArgs e)
    {
      DeleteSelect((ListView)sender, e.KeyCode);
    }

    /// <summary>
    /// ListView删除选中的项, 添加事件
    /// </summary>
    /// <param name="lsvGet"></param>
    public static void Event_KeyUpDeleteSelect(ListView lsvGet)
    {
      lsvGet.KeyUp -= ehndl_KeyUp;
      lsvGet.KeyUp += ehndl_KeyUp;
    }

    /// <summary>
    /// ListView删除选中的项,keydown事件添加
    /// </summary>
    /// <param name="lsvGet">ListView控件</param>
    /// <param name="kysGet">按键</param>
    public static void DeleteSelectEvent(ListView lsvGet)
    {
      lsvGet.KeyDown -= LsvGet_KeyDown;
      lsvGet.KeyDown += LsvGet_KeyDown;
    }

    private static void LsvGet_KeyDown(object sender, KeyEventArgs e)
    {
      DeleteSelect((ListView)sender, e.KeyCode);
    }


    /// <summary>
    /// ListView删除选中的项,keydown事件添加
    /// </summary>
    /// <param name="lsvGet">ListView控件</param>
    /// <param name="kysGet">按键</param>
    public static void DeleteSelect(ListView lsvGet, Keys kysGet = Keys.Delete)
    {
      if (kysGet == Keys.Delete && lsvGet.SelectedItems.Count != 0)
      {
        int nItemSite = 0;
        do
        {
          if (lsvGet.Items[nItemSite].Selected)
          {
            lsvGet.Items.RemoveAt(nItemSite);
          }
          else { nItemSite++; }
        }
        while (nItemSite != lsvGet.Items.Count);
      }
    }

    /// <summary>
    /// ListView添加标题
    /// </summary>
    /// <param name="lsvGet">ListView控件</param>
    /// <param name="sSet">标题字符串数组</param>
    /// <param name="nWidth">标题宽度数组</param>
    public static void AddTitile(ListView lsvGet, string[] sSet, int[] nWidth)
    {
      lsvGet.Clear();
      ColumnHeader[] clhSet = new ColumnHeader[sSet.Length];
      for (int i = 0; i < sSet.Length; i++)
      {
        clhSet[i] = new ColumnHeader()
        {
          Text = sSet[i],
          Width = nWidth[i]
        };
      }
      lsvGet.Columns.AddRange(clhSet);//将这两列加入listView1
      lsvGet.View = View.Details;//列的显示模式
      lsvGet.FullRowSelect = true;
      lsvGet.GridLines = true;
    }

    /// <summary>
    /// 读取INI文件添加到ListView
    /// </summary>
    /// <param name="lsvRead">ListView控件</param>
    /// <param name="file">INI文件路径</param>
    //public static void INIReadDatas(ListView lsvRead, string file)
    //{
    //    lsvINIReadDatas(lsvRead, file, false);
    //}

    /// <summary>
    /// 读取INI文件标题栏到ListView, 默认路径
    /// </summary>
    /// <param name="lsvRead">ListView控件</param>
    /// <param name="bolReadColumns">是否读取标题栏</param>
    //public static void INIReadDatasOnlyColumns(ListView lsvRead)
    //{
    //    lsvINIReadDatasOnlyColumns(lsvRead, CFile.GetDefaultININame());
    //}


    /// <summary>
    /// 读取INI文件标题栏到ListView
    /// </summary>
    /// <param name="lsvRead">ListView控件</param>
    /// <param name="file">INI文件路径</param>
    //public static void INIReadDatasOnlyColumns(ListView lsvRead, string file)
    //{
    //    lsvRead.Clear();
    //    //string[] strColumn = clsINIReadWrite.INIReadKeyPlus(lsvRead.Name, "Column", file);
    //    string[] strColumn = CINIReadWrite.INI_GetValue(lsvRead.Name, "Column", "", file).Split(',');
    //    //int[] intColumnWidth = clsTransform.stringsToInts(clsINIReadWrite.INIReadKeyPlus(lsvRead.Name, "ColumnWidth", file), 100);
    //    int[] intColumnWidth = CTransform.StringsToInts(CINIReadWrite.INI_GetValue(lsvRead.Name, "ColumnWidth", "", file).Split(','), 100);
    //    lsvAddTitile(lsvRead, strColumn, intColumnWidth);
    //}

    /// <summary>
    /// 读取INI文件添加到ListView
    /// </summary>
    /// <param name="lsvRead">ListView控件</param>
    /// <param name="file">INI文件路径</param>
    /// <param name="bReadColumns">是否读取标题栏</param>
    //public static void INIReadDatas(ListView lsvRead, string file, bool bReadColumns)
    //{
    //    if (bReadColumns)
    //    {
    //        lsvINIReadDatasOnlyColumns(lsvRead, file);
    //    }
    //    bool isFinish;
    //    int nPlus = 0;
    //    do
    //    {
    //        string[] strItem = CINIReadWrite.INIReadKeyPlus(lsvRead.Name, "Item" + nPlus.ToString() + "_", out isFinish, file);
    //        if (isFinish) { break; }

    //        List<string> strSet = new List<string>(strItem);
    //        for (int i = strItem.Length; i < lsvRead.Columns.Count; i++)
    //        {
    //            strSet.Add("");
    //        }
    //        lsvRead.Items.Add(new ListViewItem(strSet.ToArray()));
    //        nPlus++;
    //    } while (!isFinish);
    //    lsvRead.FullRowSelect = true;
    //}

    /// <summary>
    /// 读取INI文件添加到ListView
    /// </summary>
    /// <param name="lsvSave">ListView控件</param>
    /// <param name="file">INI文件路径</param>
    //public static void INISaveDatas(ListView lsvSave, string file)
    //{
    //    string[] stbColumn = new string[lsvSave.Columns.Count];
    //    string[] stbColumnWidth = new string[lsvSave.Columns.Count];
    //    for (int i = 0; i < lsvSave.Columns.Count; i++)
    //    {
    //        stbColumn[i] = lsvSave.Columns[i].Text;
    //        stbColumnWidth[i] = lsvSave.Columns[i].Width.ToString();

    //        //clsINIReadWrite.INISetValue(lsvSave.Name, "Column" + i.ToString(), lsvSave.Columns[i].Text, file);
    //        //clsINIReadWrite.INISetValue(lsvSave.Name, "ColumnWidth" + i.ToString(), lsvSave.Columns[i].Width.ToString(), file);
    //    }
    //    CINIReadWrite.INISetValue(lsvSave.Name, "Column", CArray.StringsInsertString(stbColumn, ","), file);
    //    CINIReadWrite.INISetValue(lsvSave.Name, "ColumnWidth", CArray.StringsInsertString(stbColumnWidth, ","), file);
    //    for (int j = 0; j < lsvSave.Items.Count; j++)
    //    {
    //        for (int i = 0; i < lsvSave.Columns.Count; i++)
    //        {
    //            try
    //            {
    //                string sNew2 = lsvSave.Items[j].SubItems[i].Text;
    //                CINIReadWrite.INISetValue(lsvSave.Name, "Item" + j.ToString() + "_" + i.ToString(), sNew2, file);
    //            }
    //            catch
    //            { }
    //        }
    //    }
    //    CINIReadWrite.INISetValue(lsvSave.Name, "Item" + lsvSave.Items.Count.ToString() + "_0", "#.null#", file);
    //}

    /// <summary>
    /// ListView添加以指定字符分割的列表
    /// </summary>
    /// <param name="sAddList">添加的列表</param>
    /// <param name="lsvGet">ListView</param>
    /// <param name="SplitChars">列表的分隔符分隔</param>
    public static void AddEqualValues(string[] sAddList, ListView lsvGet, string SplitChars = "=")
    {
      List<ListViewItem> lviList = new List<ListViewItem>();
      for (int i = 0; i < sAddList.Length; i++)
      {
        lviList.Add(new ListViewItem(Split(sAddList[i], SplitChars)));
      }
      lsvGet.Items.AddRange(lviList.ToArray());
    }
  #endregion

  #region Libs
    /// <summary>
    /// 分割字符串
    /// </summary>
    /// <param name="Text">分割的文本</param>
    /// <param name="Split">分割的标志</param>
    /// <returns>返回字符串数组</returns>
    private static string[] Split(string Text, string Split, int EnsureCount = 0)
    {
      int nSplitSite, nPreviousSite = -Split.Length, start = 0;
      if (Text == null)
      {
        Text = "";
      }
      List<string> lsdget = new List<string>();
      do
      {
        nSplitSite = Text.IndexOf(Split, start);
        if (nSplitSite == -1)
        {
          lsdget.Add(GetSubString(Text, nPreviousSite + Split.Length));
          break;
        }
        lsdget.Add(Text.Substring(start, nSplitSite - start));
        start = nSplitSite + Split.Length;
        nPreviousSite = nSplitSite;
      } while (true);
      if (EnsureCount > 0)
      {
        EnsureCount -= lsdget.Count;
        if (EnsureCount > 0)
        {
          for (int i = 0; i < EnsureCount; i++)
          {
            lsdget.Add("");
          }
        }
      }
      return lsdget.ToArray();
    }

    /// <summary>
    /// 比较字符串的大小,按char逐位比较
    /// </summary>
    /// <param name="CompA">字符串A</param>
    /// <param name="CompB">字符串B</param>
    /// <returns>A>B返回1,A=B返回0,其他返回-1</returns>
    public static int StringCompare_ASCIIPriority(string CompA, string CompB)
    {
      char[] cSplitA, cSplitB;
      if (CompA.Length == CompB.Length)
      {
        return 0;
      }
      cSplitA = CompA.ToCharArray();
      cSplitB = CompB.ToCharArray();
      for (int i = 0; i < Math.Min(CompA.Length, CompB.Length); i++)
      {
        if (cSplitA[i] > cSplitB[i])
        {
          return 1;
        }
        else if (cSplitA[i] < cSplitB[i])
        {
          return -1;
        }
      }
      return 0;
    }


    /// <summary>
    /// 比较字符串的大小,长度大的大,长度相等的,按char逐位比较
    /// </summary>
    /// <param name="CompA">字符串A</param>
    /// <param name="CompB">字符串B</param>
    /// <returns>A>B返回1,A=B返回0,其他返回-1</returns>
    public static int StringCompare_LengthPrioity(string CompA, string CompB)
    {
      char[] cSplitA, cSplitB;
      if (CompA.Length > CompB.Length)
      {
        return 1;
      }
      else if (CompA.Length < CompB.Length)
      {
        return -1;
      }
      else
      {
        cSplitA = CompA.ToCharArray();
        cSplitB = CompB.ToCharArray();
        for (int i = 0; i < CompA.Length; i++)
        {
          if (cSplitA[i] > cSplitB[i])
          {
            return 1;
          }
          else if (cSplitA[i] < cSplitB[i])
          {
            return -1;
          }
        }
      }
      return 0;
    }

    /// <summary>
    /// 交换两个字符串
    /// </summary>
    /// <param name="sSwapA">字符串A</param>
    /// <param name="sSwapB">字符串B</param>
    public static void Swap(ref string sSwapA, ref string sSwapB)
    {
      string sTemp;
      sTemp = sSwapA;
      sSwapA = sSwapB;
      sSwapB = sTemp;
    }

    /// <summary>
    /// 获取字符串内的内容
    /// </summary>
    /// <param name="dGet">字符串</param>
    /// <param name="offset">偏移量</param>
    /// <param name="count">数量, 如count<0, 则向前取字符串</param>
    /// <returns>结果</returns>
    public static string GetSubString(string dGet, int offset = 0, int count = int.MaxValue)
    {
      char[] tmp;
      if ((dGet.Length == 0) || (dGet.Length <= offset))//偏移量超过长度....明显输入错误
      {
        return "";
      }
      if (count == int.MaxValue)
      {
        count = dGet.Length - offset;
      }
      else if (count < 0)
      {
        count = -count;
        var ct = offset - count;
        if (ct <= 0)
        {
          count = offset + 1;
          offset = 0;
        }
        else
        {
          offset = ct + 1;
        }
      }
      if (dGet.Length < offset + count)
      {
        count = dGet.Length - offset;
      }
      tmp = dGet.ToCharArray(offset, count);
      return new string(tmp);
    }

    /// <summary>
    /// [C] 字符串转成数字
    /// </summary>
    /// <param name="dget">字符串</param>
    /// <param name="offset">偏移量</param>
    /// <param name="count">转换的个数,0为不限</param>
    /// <returns>返回int</returns>
    public static int StringToInt(string dget, int offset = 0, int count = -1)
    {
      int dSum;
      return StringToInt(dget, out dSum, offset, count);
    }


    /// <summary>
    /// [C] 字符串转成数字
    /// </summary>
    /// <param name="dget">字符串</param>
    /// <param name="dSum">返回的位数</param>
    /// <param name="count">转换的个数,0为不限</param>
    /// <param name="offset">偏移量</param>
    /// <returns>返回int</returns>
    public static int StringToInt(string dget, out int dSum, int offset = 0, int count = -1)
    {
      int nResult = 0;
      bool negative = false;
      int sum = offset;
      if (dget == "" || dget == null || offset >= dget.Length)
      {
        dSum = 0;
        return 0;
      }
      if (dget[offset] == '-')
      {
        negative = true;
        sum++;
      }
      else if (dget[offset] == '+')
      {
        sum++;
      }
      try
      {
        while ((dget[sum] >= '0') && (dget[sum] <= '9') && (sum != count || count == 0))
        {
          nResult = nResult * 10 + (dget[sum++] - '0');
        }
      }
      catch { }
      dSum = sum - offset;
      return negative ? -nResult : nResult;
    }


  #endregion
  }
}
